#!/usr/bin/bash
set -e

GITHUB_URL=https://github.com/elastic/beats/releases

DOWNLOADER=
LOCAL_PATH=$(dirname $0)


my_info(){
    echo "$(date +'%F %T') [INFO] " "$@"
}
fatal(){
    echo "$(date +'%F %T') [ERROR] " "$@"
    exit 1
}

# --- create tempory directory and cleanup when done ---
setup_tmp() {
    TMP_DIR=$(mktemp -d -t exporter-install.XXXXXXXXXX)
    cleanup() {
        code=$?
        set +e
        trap - EXIT
        rm -rf ${TMP_DIR}
        exit $code
    }
    trap cleanup INT EXIT
}

get_release_version() {
  my_info "Finding latest release"
  case $DOWNLOADER in
      curl)
          VERSION_NODE_EXPORTER=$(curl -w '%{url_effective}' -I -L -s -S ${GITHUB_URL}/latest -o /dev/null | sed -e 's|.*/||')
          ;;
      wget)
          VERSION_NODE_EXPORTER=$(wget -SqO /dev/null ${GITHUB_URL}/latest 2>&1 | grep Location | sed -e 's|.*/||')
          ;;
      *)
          fatal "Incorrect downloader executable '$DOWNLOADER'"
          ;;
  esac
}

verify_downloader() {
    # Return failure if it doesn't exist or is no executable
    [ -x "$(which $1)" ] || return 1

    # Set verified executable as our downloader program and return success
    DOWNLOADER=$1
    return 0
}
# --- download from github url ---
download() {
    [ $# -eq 2 ] || fatal 'download needs exactly 2 arguments'

    case $DOWNLOADER in
        curl)
            curl -o $1 -sfL $2
            ;;
        wget)
            wget -qO $1 $2
            ;;
        *)
            fatal "Incorrect executable '$DOWNLOADER'"
            ;;
    esac

    # Abort if download command failed
    [ $? -eq 0 ] || fatal 'Download failed'
}

filebeat_oss_main(){

  verify_downloader curl \
    || verify_downloader wget \
    || fatal 'Can not find curl or wget for downloading files'
  setup_tmp

  get_release_version
  TAR_PACKET=filebeat-oss-${VERSION_NODE_EXPORTER#*v}-linux-x86_64
  DOWNLOAD_URL=https://artifacts.elastic.co/downloads/beats/filebeat/${TAR_PACKET}.tar.gz
  HASH_URL=${DOWNLOAD_URL}.sha512

  download ${TMP_DIR}/sha512sum ${HASH_URL}
  download ${TMP_DIR}/${TAR_PACKET}.tar.gz ${DOWNLOAD_URL}
  HASH_INSTALLED=$(sha512sum ${TMP_DIR}/${TAR_PACKET}.tar.gz | awk '{print $1}')
  HASH_EXPECTED=$(grep " ${TAR_PACKET}.tar.gz$" ${TMP_DIR}/sha512sum | awk '{print $1}')
  if [ "${HASH_EXPECTED}" != "${HASH_INSTALLED}" ]; then
    fatal "Download sha512sum does not match ${HASH_EXPECTED}, got ${HASH_BIN}"
  fi

  if [[ -z "${DOWNLOAD_PATH}" ]] ; then
    cp -f ${TMP_DIR}/${TAR_PACKET}.tar.gz ${LOCAL_PATH}/
  else
    cp -f ${TMP_DIR}/${TAR_PACKET}.tar.gz ${DOWNLOAD_PATH}/
  fi
}

filebeat_oss_main